<?php
/**
 * Created by PhpStorm.
 * User: saeb
 * Date: 12/10/18
 * Time: 3:12 AM
 */
require(tiremanager_plugin_dir_path . 'formsconfig.php');
if ($tire_ware_house_limit) {

    add_filter('gform_confirmation_' . $tire_gravity_form_id, 'set_warehouse_capacity', 10, 4);
}
function set_warehouse_capacity($confirmation, $form, $entry)
{
    error_log("we are in custom confirm");
    require(tiremanager_plugin_dir_path . 'formsconfig.php');
    require(tiremanager_plugin_dir_path . 'sellers_brands.php');
    global $wpdb;
    $table_name=$wpdb->prefix.$tire_table_quantities_without_prefix_name;
    $tire_size = "";
    $tire_brand = "";
    $tire_seller = "";
    $tire_quantity = 0;
    foreach ($tire_gf_fields_id_sellers_array as $tire_sabok_seller_gf_field_id => $value) {
        $tire_seller = $tire_seller . rgar($entry, "$tire_sabok_seller_gf_field_id");

    }
    foreach ($sellers_array[$tire_seller]['tire_type'] as $type) {

        foreach ($tire_gf_fields_id_tire_sizes[$type] as $tire_sabok_size_gf_field_id => $value) {
            $tire_size = $tire_size . rgar($entry, "$tire_sabok_size_gf_field_id");
        }
    }
    foreach ($tire_gf_fields_id_brands_array as $tire_sabok_brand_gf_field_id => $value) {
        $tire_brand = $tire_brand . rgar($entry, "$tire_sabok_brand_gf_field_id");

    }
    foreach ($tire_gf_fields_id_quantity_asked as $tire_quantity_gf_field_id => $value) {
        $tire_quantity = $tire_quantity + intval(rgar($entry, $tire_quantity_gf_field_id));

    }


    $available_tires = $wpdb->get_row("
    select `id`,`tire_quantity`, `added_by` from $table_name
    where id = (
SELECT max(id) from $table_name where 
    `tire_seller` = '$tire_seller'
    and `tire_size`= '$tire_size' 
    and `tire_brand`= '$tire_brand'
)
    ;");
    $anbar=$available_tires->tire_quantity;
    $added_by=$available_tires->added_by;
    $row_id=$available_tires->id;
    error_log(print_r($anbar.$added_by,true));
    $date = date('Y-m-d H:i:s');
    if ($added_by != "gravity_forms"){
        $table_data=array(
            'tire_seller'=>$tire_seller,
            'tire_size'=>$tire_size,
            'tire_quantity'=>$anbar-$tire_quantity,
            'tire_brand'=>$tire_brand,
            'added_by'=>"gravity_forms",
            'date_updated'=>$date ,
        );
        $wpdb->insert($table_name,$table_data);
    }
    else {
        $table_data=array(
            'tire_seller'=>$tire_seller,
            'tire_size'=>$tire_size,
            'tire_quantity'=>$anbar-$tire_quantity,
            'tire_brand'=>$tire_brand,
            'date_updated'=>$date ,

//            'added_by'=>"gravity_forms",
        );
        $wpdb->update($table_name,$table_data,array( 'id' =>  $row_id ) );
    }
        return $confirmation;


}
